package org.sgx.gapigui.client.ui.actions.books;

import java.util.List;

import org.sgx.gapigui.client.Main;
import org.sgx.gapigui.client.control.ControllerCallback;
import org.sgx.gapigui.client.ui.editableModels.books.Book;
import org.sgx.gapigui.client.ui.editableModels.ft.Table;
import org.sgx.gwteditors.client.impl1.complex.PropertyHaverTableEditor1;
import org.sgx.jsutil.client.DOMUtil;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.ButtonElement;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class BookSearch extends Composite {

	private static BookSearchUiBinder uiBinder = GWT.create(BookSearchUiBinder.class);

	interface BookSearchUiBinder extends UiBinder<Widget, BookSearch> {
	}
	
	@UiField InputElement searchKeywords; 
//	@UiField ButtonElement searchButton; 
	@UiField VerticalPanel resultListContainer; 
	
	@UiField Button searchButton; 

	public BookSearch() {

		initWidget(uiBinder.createAndBindUi(this));
		searchButton.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				Main.controller().doBookSearch(searchKeywords.getValue(), new ControllerCallback<List<Book>>() {
					
					@Override
					public void call(List<Book> result) {
						System.out.println("RESULT: "+result.size());
						for(Book b : result) {
							b.getProperties().reorder(new String[]{"title", "authorName", "description", "language"}); 
						}
						Book[] resultarr = result.toArray(new Book[]{});
//						Window.alert(result.size()+", "+resultarr.length);
						PropertyHaverTableEditor1<Book> ed = new PropertyHaverTableEditor1<Book>();//EditorFramework1.TYPE_PROPERTYHAVER, null, null);
						ed.load(resultarr); 
						resultListContainer.clear();
						resultListContainer.add(ed);
					}
				}); 
			}
		}); 
//		DOMUtil.addClickHandler(searchButton, new DOMUtil.EventHandler() {			
//			@Override
//			public void onEvent(Event event) {
//				
//			}
//		}); 
	}

}
